package main

import (
	"context"
	"google.golang.org/grpc"
	pb "helloworld/helloworld"
	"io"
	"log"
	"time"
)

func main() {
	target := "localhost:8009"
	conn, err := grpc.Dial(target, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

	client := pb.NewGreeterClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	// 发送单个请求
	r, err := client.SayHello(ctx, &pb.HelloRequest{Name: "crissu", Age: 25})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r.GetMessage())

	// 发送流式请求
	videoRequests := []*pb.VideoRequest{
		{Name: "凡人修仙传", Tag: "修仙"},
		{Name: "斗罗大陆", Tag: "修仙"},
		{Name: "喜羊羊与灰太狼", Tag: "动画"},
		{Name: "大明王朝1566", Tag: "历史"},
	}
	ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	stream, err := client.RequestVideo(ctx)
	if err != nil {
		log.Fatalf("%v.RequestVideo(_) = _, %v", client, err)
	}
	wait := make(chan struct{})
	go func() {
		for {
			in, err := stream.Recv()
			if err == io.EOF {
				// read done.
				close(wait)
				return
			}
			if err != nil {
				log.Fatalf("Failed to receive a note : %v", err)
			}
			log.Printf("Got message [name:%s; url:%s; time_length:%d]", in.Name, in.Url, in.TimeLength)
		}
	}()
	for _, videwRequest := range videoRequests {
		if err := stream.Send(videwRequest); err != nil {
			log.Fatalf("Failed to send a note: %v", err)
		}
	}
	stream.CloseSend()
	<-wait
}
